package com.fau.cm.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.fau.cm.entity.MedicalAdmin;
import com.fau.cm.entity.MedicalCall;
import com.fau.cm.entity.MedicalCallContactRecord;
import com.fau.cm.entity.MedicalCallCustomer;
import com.fau.cm.entity.MedicalCallCustomerHealth;
import com.fau.cm.entity.MedicalCallCustomerReminder;
import com.fau.cm.entity.MedicalCallEnd;
import com.fau.cm.entity.MedicalCallHealthSymptom;
import com.fau.cm.entity.MedicalCallPending;
import com.fau.cm.entity.MedicalCallTelInfo;
import com.fau.cm.entity.MedicalCallTerminate;
import com.fau.cm.entity.MedicalCallUntreated;
import com.fau.cm.entity.MedicalCity;
import com.fau.cm.entity.MedicalDistrict;
import com.fau.cm.entity.MedicalKeyValue;
import com.fau.cm.entity.MedicalMediaPlacement;
import com.fau.cm.entity.MedicalOrdersStorage;
import com.fau.cm.entity.MedicalProvince;
import com.fau.cm.service.ICustomerManagerService;
import com.fau.cm.util.HttpRequestUtil;
import com.fau.cm.util.Page;
import com.fau.cm.util.ParamUtil;
import com.fau.cm.util.PhoneNumUtil;
import com.fau.cm.util.SerialNumUtil;
import com.fau.cm.util.SystemConfig;

@Service
@Transactional(readOnly = true)
public class CustomerManagerService extends BaseService implements ICustomerManagerService{
	
	@Resource
	private HttpRequestUtil httpRequestUtil;

	@Override
	public Page findCustomerByPage(MedicalAdmin admin, MedicalCallCustomer customer, Map<String, Object> map) {
		StringBuilder countSql = new StringBuilder("select count(*) from MedicalCallCustomer m where m.hospitalId=? ");
		StringBuilder statusSql = new StringBuilder("from MedicalCallCustomer m where m.hospitalId=? ");
		
		List<Object> objectList = new ArrayList<Object>();
		objectList.add(admin.getEnterpriseId());
		
		if(StringUtils.isNotBlank(customer.getName())){
			String name = customer.getName().replaceAll("_", "chr(95)").replaceAll("%", "chr(37)");
			countSql.append("and m.name like ? ");
			statusSql.append("and m.name like ? ");
			objectList.add("%"+name+"%");
		}
		
		if(StringUtils.isNotBlank(customer.getSex())){
			countSql.append("and m.sex = ? ");
			statusSql.append("and m.sex = ? ");
			objectList.add(customer.getSex());
		}
		
		if(StringUtils.isNotBlank(customer.getCustomerLevel())){
			countSql.append("and m.customerLevel = ? ");
			statusSql.append("and m.customerLevel = ? ");
			objectList.add(customer.getCustomerLevel());
		}
		
		if(StringUtils.isNotBlank(customer.getSerialNum())){
			countSql.append("and m.serialNum = ? ");
			statusSql.append("and m.serialNum = ? ");
			objectList.add(customer.getSerialNum());
		}
		
		if(StringUtils.isNotBlank(customer.getCustomersSource())){
			countSql.append("and m.customersSource = ? ");
			statusSql.append("and m.customersSource = ? ");
			objectList.add(customer.getCustomersSource());
		}
		
		if(StringUtils.isNotBlank(customer.getContactNo())){
			MedicalCallTelInfo telInfo = (MedicalCallTelInfo) this.iBaseDao.getObjectByHql("from MedicalCallTelInfo a where a.phoneNum=? and a.eid=? ", customer.getContactNo(),admin.getEnterpriseId());
			if(null == telInfo){
				countSql.append("and m.id = null ");
				statusSql.append("and m.id = null ");
			}else{
				countSql.append("and m.id = ? ");
				statusSql.append("and m.id = ? ");
				objectList.add(telInfo.getCustomerId());
			}
			
		}
		
		statusSql.append("order by m.createTime desc ");
		
		Page page = this.iBaseDao.getPage(ParamUtil.getInteger(map,"pageIndex",1),ParamUtil.getInteger(map, "pageSize", 20),
				map, countSql.toString(), statusSql.toString(), objectList);
		List<MedicalCallCustomer> list = new ArrayList<MedicalCallCustomer>();
		for(Object obj : page.getResult()){
			customer = (MedicalCallCustomer)obj;
			MedicalCallTelInfo telInfo = (MedicalCallTelInfo) this.iBaseDao.getObjectByHql("from MedicalCallTelInfo a where a.customerId=? and a.isMain=? ", customer.getId(),SystemConfig.CUSTOMER_TEL_IS_MAIN);
			if(null != telInfo){
				customer.setContactNo(telInfo.getPhoneNum());
			}
			if(StringUtils.isNotBlank(customer.getRecommendId())) {
				MedicalCallCustomer recommend = (MedicalCallCustomer) this.iBaseDao.getObject(MedicalCallCustomer.class, customer.getRecommendId());
				customer.setRecommendName(recommend.getName());
			}
			MedicalKeyValue keyVal = (MedicalKeyValue)this.iBaseDao.getValueByKey(admin.getEnterpriseId(), customer.getSex());
			MedicalKeyValue customersSource = (MedicalKeyValue)this.iBaseDao.getValueByKey(admin.getEnterpriseId(), customer.getCustomersSource());
			MedicalKeyValue customerLevel = (MedicalKeyValue)this.iBaseDao.getValueByKey(admin.getEnterpriseId(), customer.getCustomerLevel());
			MedicalKeyValue journal = (MedicalKeyValue)this.iBaseDao.getValueByKey(admin.getEnterpriseId(), customer.getJournal());
			if(null != keyVal) {
				customer.setKeySex(keyVal.getKeyValue());
			}
			if(customersSource != null){
				customer.setKeyCustomersSource(customersSource.getKeyValue());
			}
			if(customerLevel != null){
				customer.setKeyCustomerLevel(customerLevel.getKeyValue());
			}
			if(journal != null){
				customer.setKeyJournal(journal.getKeyValue());
			}
			list.add(customer);
		}
		page.setResult(list);
		return page;
	}
		
	@Override
	public Page findGroupCustomerByPage(MedicalAdmin admin,MedicalCallCustomer customer,Map<String, Object> map){
		List<Object> objectList = new ArrayList<Object>();
		StringBuilder countSql = new StringBuilder("select count(*) from MedicalCallCustomer m where 1=1 and m.hospitalId=? ");
		StringBuilder statusSql = new StringBuilder("from MedicalCallCustomer m where 1=1 and m.hospitalId=? and m.groupId=?");
		objectList.add(admin.getEnterpriseId());
		if(!SystemConfig.SUPER_ADMIN.equals(admin.getIsSuper())) {
			countSql.append(" and m.groupId=? ");
			statusSql.append(" and m.groupId=? ");
			objectList.add(admin.getGroup().getId());
		}
		objectList.add(admin.getGroup().getId());
		if(StringUtils.isNotBlank(customer.getName())){
			countSql.append("and m.name like ? ");
			statusSql.append("and m.name like ? ");
			objectList.add("%"+customer.getName()+"%");
		}
		if(customer.getSex() != null){
			countSql.append("and m.sex = ? ");
			statusSql.append("and m.sex = ? ");
			objectList.add(customer.getSex());
		}
		statusSql.append("order by m.recordingTime desc ");
		Page page = this.iBaseDao.getPage(ParamUtil.getInteger(map,"pageIndex",1),ParamUtil.getInteger(map, "pageSize", 20),
				map, countSql.toString(), statusSql.toString(), objectList);
		List<MedicalCallCustomer> list = new ArrayList<MedicalCallCustomer>();
		for(Object obj : page.getResult()){
			customer = (MedicalCallCustomer)obj;
			MedicalKeyValue keyVal = (MedicalKeyValue)this.iBaseDao.getValueByKey(admin.getEnterpriseId(), customer.getSex());
			MedicalKeyValue customersSource = (MedicalKeyValue)this.iBaseDao.getValueByKey(admin.getEnterpriseId(), customer.getCustomersSource());
			MedicalKeyValue customerLevel = (MedicalKeyValue)this.iBaseDao.getValueByKey(admin.getEnterpriseId(), customer.getCustomerLevel());
			MedicalKeyValue journal = (MedicalKeyValue)this.iBaseDao.getValueByKey(admin.getEnterpriseId(), customer.getJournal());
			if(null != keyVal){
				customer.setKeySex(keyVal.getKeyValue());
			}
			if(null != customersSource){
			customer.setKeyCustomersSource(customersSource.getKeyValue());
			}
			if(null != customerLevel){
			customer.setKeyCustomerLevel(customerLevel.getKeyValue());
			}
			if(null != journal){
			customer.setKeyJournal(journal.getKeyValue());
			}
			list.add(customer);
		}
		page.setResult(list);
		return page;
	}
	
	@Override
	public Page findMyCustomerByPage(MedicalAdmin admin, MedicalCallCustomer customer,	Map<String, Object> map) {
		List<Object> objectList = new ArrayList<Object>();
		StringBuilder countSql = new StringBuilder("select count(*) from MedicalCallCustomer m where 1=1 and m.userId=? and m.hospitalId=? ");
		StringBuilder statusSql = new StringBuilder("from MedicalCallCustomer m where 1=1 and m.userId=? and m.hospitalId=? ");
		objectList.add(admin.getId());
		objectList.add(admin.getEnterpriseId());
		statusSql.append("order by m.recordingTime desc ");
		Page page = this.iBaseDao.getPage(ParamUtil.getInteger(map,"pageIndex",1),ParamUtil.getInteger(map, "pageSize", 20),
				map, countSql.toString(), statusSql.toString(), objectList);
		List<MedicalCallCustomer> list = new ArrayList<MedicalCallCustomer>();
		for(Object obj : page.getResult()){
			customer = (MedicalCallCustomer)obj;
			MedicalKeyValue keyVal = (MedicalKeyValue)this.iBaseDao.getValueByKey(admin.getEnterpriseId(), customer.getSex());
			MedicalKeyValue customersSource = (MedicalKeyValue)this.iBaseDao.getValueByKey(admin.getEnterpriseId(), customer.getCustomersSource());
			MedicalKeyValue customerLevel = (MedicalKeyValue)this.iBaseDao.getValueByKey(admin.getEnterpriseId(), customer.getCustomerLevel());
			MedicalKeyValue journal = (MedicalKeyValue)this.iBaseDao.getValueByKey(admin.getEnterpriseId(), customer.getJournal());
			customer.setKeySex(keyVal.getKeyValue());
			if(customersSource != null){
				customer.setKeyCustomersSource(customersSource.getKeyValue());
			}
			if(customerLevel != null){
				customer.setKeyCustomerLevel(customerLevel.getKeyValue());
			}
			if(journal != null){
				customer.setKeyJournal(journal.getKeyValue());
			}
			list.add(customer);
		}
		page.setResult(list);
		return page;
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public String importCustomer(MedicalAdmin admin, MedicalCallCustomer customer, File file) throws Exception {
		String info = null;
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();
		Sheet sheet =  workbook.getSheetAt(0);
		//遍历每行
		for (Row row : sheet) {
			String name = null; 			// 姓名
			String phone = null; 			// 电话
			String sex = null; 				// 性别
			Date recordingTime = null; 		// 记录时间
			int i = row.getRowNum()+1;
			if(row.getRowNum() > 0){ 
				if(row.getCell(0) == null){
					info="第"+i+"行姓名不能为空！";
					break;
				}else{
					name = row.getCell(0).getStringCellValue().trim(); //姓名
				}
				
				if(row.getCell(1) == null){
					info="第"+i+"行电话号码不能为空！";
					break;
				}else{
					if(HSSFCell.CELL_TYPE_STRING == row.getCell(1).getCellType()){
						phone = row.getCell(1).getStringCellValue().trim(); //电话    
					}else{
						phone = String.format("%.0f",row.getCell(1).getNumericCellValue());
					}
				}
				
				if(row.getCell(2) == null){
					info="第"+i+"行性别不能为空！";
					break;
				}else{
					sex = row.getCell(2).getStringCellValue().trim(); //性别
					if("男".equals(sex)){
						sex = "8";
					}else if("女".equals(sex)){
						sex = "9";
					}else{
						sex = "10";
					}
					
				}
				if(row.getCell(3) == null){
					info="第"+i+"行记录时间不能为空！";
					break;
				}else{
					if(HSSFCell.CELL_TYPE_NUMERIC != row.getCell(3).getCellType()){
						info="第"+i+"行记录时间格式错误！";
						break;
					}else{
						recordingTime = row.getCell(3).getDateCellValue(); //记录时间
					}
				}
				//判断电话是否重复
				MedicalCallTelInfo callTelInfo = (MedicalCallTelInfo) this.iBaseDao.getObjectByHql("from MedicalCallTelInfo a where a.eid=? and a.phoneNum=? ", admin.getEnterpriseId(),phone);
				if(callTelInfo == null){
					String validNum = PhoneNumUtil.checkNumber(phone).toString();
					String type = "";
					if(SystemConfig.CELLPHONE_TYPE.equals(validNum.substring(0, validNum.lastIndexOf(",")))) {
						type = SystemConfig.CUSTOMER_TEL_PHONE_TYPE;
					} else if(SystemConfig.FIXEDPHONE_TYPE.equals(validNum.substring(0, validNum.lastIndexOf(",")))) {
						type = SystemConfig.CUSTOMER_TEL_FIXED_TYPE;
					} 
					
					if(StringUtils.isNotBlank(type)) {
						customer = new MedicalCallCustomer();
						customer.setSerialNum(SerialNumUtil.code());
						customer.setName(name);
						customer.setSex(sex);
						customer.setRecordingTime(recordingTime);
						customer.setCustomerLevel(SystemConfig.CUSTOMER_LEVEL_INIT);
						customer.setCustomersSource(SystemConfig.CUSTOMER_SOURCE_IMPORT_TYPE);
						customer.setHospitalId(admin.getEnterpriseId());
						this.iBaseDao.saveObject(customer);
						
						MedicalCallTelInfo telInfo = new MedicalCallTelInfo();
						telInfo.setType(type);
						telInfo.setPhoneNum(phone);
						telInfo.setIsMain(SystemConfig.CUSTOMER_TEL_IS_MAIN);
						telInfo.setCustomerId(customer.getId());
						telInfo.setEid(admin.getEnterpriseId());
						this.iBaseDao.saveObject(telInfo);
					} else {
						info="第"+i+"行号码格式不正确！";
						break;
					}
				}else{
					info="第"+i+"行电话已经在系统中！";
					break;
				}
			}	//跳过标题和表头end
		}
		return info;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Workbook exportCustomer(MedicalAdmin admin,MedicalCallCustomer customer) throws Exception {
		StringBuilder statusSql = new StringBuilder("from MedicalCallCustomer m where m.hospitalId=? ");
		
		List<Object> objectList = new ArrayList<Object>();
		objectList.add(admin.getEnterpriseId());
		
		if(StringUtils.isNotBlank(customer.getName())){
			String name = customer.getName().replaceAll("_", "chr(95)").replaceAll("%", "chr(37)");
			statusSql.append("and m.name like ? ");
			objectList.add("%"+name+"%");
		}
		
		if(StringUtils.isNotBlank(customer.getSex())){
			statusSql.append("and m.sex = ? ");
			objectList.add(customer.getSex());
		}
		
		if(StringUtils.isNotBlank(customer.getCustomerLevel())){
			statusSql.append("and m.customerLevel = ? ");
			objectList.add(customer.getCustomerLevel());
		}
		
		if(StringUtils.isNotBlank(customer.getSerialNum())){
			statusSql.append("and m.serialNum = ? ");
			objectList.add(customer.getSerialNum());
		}
		
		if(StringUtils.isNotBlank(customer.getCustomersSource())){
			statusSql.append("and m.customersSource = ? ");
			objectList.add(customer.getCustomersSource());
		}
		
		statusSql.append("order by m.recordingTime desc ");
		
		List<MedicalCallCustomer> list = this.iBaseDao.getBySql(statusSql.toString(), null, objectList.toArray());
		
		// Excel模版对象
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_CALL_CUSTOMER);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();
		Sheet sheet = workbook.getSheetAt(0);
		// 遍历
		int size = list.size();
		for (int i = 0;i < size;i++) {
			Row currentRow = sheet.createRow(i+1);
			if(StringUtils.isNotBlank(list.get(i).getSerialNum())){
				currentRow.createCell(0).setCellValue(list.get(i).getSerialNum());
			}
			if(StringUtils.isNotBlank(list.get(i).getName())){
				currentRow.createCell(1).setCellValue(list.get(i).getName());
			}
			if(StringUtils.isNotBlank(list.get(i).getSex())){
				MedicalKeyValue sexKV = this.iBaseDao.getValueByKey(admin.getEnterpriseId(), list.get(i).getSex());
				if(null != sexKV){
					currentRow.createCell(2).setCellValue(sexKV.getKeyValue());
				}
			}
			if(StringUtils.isNotBlank(list.get(i).getCustomersSource())){
				MedicalKeyValue customersSourceKV = this.iBaseDao.getValueByKey(admin.getEnterpriseId(), list.get(i).getCustomersSource());
				if(null != customersSourceKV){
					currentRow.createCell(3).setCellValue(customersSourceKV.getKeyValue());
				}
			}
			if(null != list.get(i).getRecordingTime()){
				currentRow.createCell(4).setCellValue(list.get(i).getRecordingTime());
			}
			if(StringUtils.isNotBlank(list.get(i).getCustomerServiceId())){
				MedicalAdmin medicalAdmin = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, list.get(i).getCustomerServiceId());
				if(null != medicalAdmin){
					currentRow.createCell(5).setCellValue(medicalAdmin.getName());
				}
			}
			if(StringUtils.isNotBlank(list.get(i).getCustomerLevel())){
				MedicalKeyValue customerLevelKV = this.iBaseDao.getValueByKey(admin.getEnterpriseId(), list.get(i).getCustomerLevel());
				if(null != customerLevelKV){
					currentRow.createCell(6).setCellValue(customerLevelKV.getKeyValue());
				}
			}
			if(StringUtils.isNotBlank(list.get(i).getRemarks())){
				currentRow.createCell(7).setCellValue(list.get(i).getRemarks());
			}
			if(StringUtils.isNotBlank(list.get(i).getProvinceId())){
				MedicalProvince province = (MedicalProvince) this.iBaseDao.getObject(MedicalProvince.class, list.get(i).getProvinceId());
				if(null != province){
					currentRow.createCell(8).setCellValue(province.getpName());
				}
			}
			if(StringUtils.isNotBlank(list.get(i).getCityId())){
				MedicalCity city = (MedicalCity) this.iBaseDao.getObject(MedicalCity.class, list.get(i).getCityId());
				currentRow.createCell(9).setCellValue(city.getcName());
			}
			if(StringUtils.isNotBlank(list.get(i).getDistrictId())){
				MedicalDistrict district = (MedicalDistrict) this.iBaseDao.getObject(MedicalDistrict.class, list.get(i).getDistrictId());
				if(null != district){
					currentRow.createCell(10).setCellValue(district.getdName());
				}
			}
			if(StringUtils.isNotBlank(list.get(i).getAddress())){
				currentRow.createCell(11).setCellValue(list.get(i).getAddress());
			}
		}
		return workbook;
	}

	@Override
	public Workbook currentExportCustomer(MedicalAdmin admin, String ids) throws Exception {
		// Excel模版对象
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_CALL_CUSTOMER);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}	
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();
		Sheet sheet = workbook.getSheetAt(0);
		if(StringUtils.isNotBlank(ids)){
			String [] ordersIds =  ids.split(",");
			for(int j=0;j<ordersIds.length;j++){
				// 获得记录
				MedicalCallCustomer customer = (MedicalCallCustomer)this.iBaseDao.getObject(MedicalCallCustomer.class, ordersIds[j]);
				Row currentRow = sheet.createRow(j+1);
				if(StringUtils.isNotBlank(customer.getSerialNum())){
					currentRow.createCell(0).setCellValue(customer.getSerialNum());
				}
				if(StringUtils.isNotBlank(customer.getName())){
					currentRow.createCell(1).setCellValue(customer.getName());
				}
				if(StringUtils.isNotBlank(customer.getSex())){
					MedicalKeyValue sexKV = this.iBaseDao.getValueByKey(admin.getEnterpriseId(), customer.getSex());
					if(null != sexKV){
						currentRow.createCell(2).setCellValue(sexKV.getKeyValue());
					}
				}
				if(StringUtils.isNotBlank(customer.getCustomersSource())){
					MedicalKeyValue customersSourceKV = this.iBaseDao.getValueByKey(admin.getEnterpriseId(), customer.getCustomersSource());
					if(null != customersSourceKV){
						currentRow.createCell(3).setCellValue(customersSourceKV.getKeyValue());
					}
				}
				if(null != customer.getRecordingTime()){
					currentRow.createCell(4).setCellValue(customer.getRecordingTime());
				}
				if(StringUtils.isNotBlank(customer.getCustomerServiceId())){
					MedicalAdmin medicalAdmin = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, customer.getCustomerServiceId());
					if(null != medicalAdmin){
						currentRow.createCell(5).setCellValue(medicalAdmin.getName());
					}
				}
				if(StringUtils.isNotBlank(customer.getCustomerLevel())){
					MedicalKeyValue customerLevelKV = this.iBaseDao.getValueByKey(admin.getEnterpriseId(), customer.getCustomerLevel());
					if(null != customerLevelKV){
						currentRow.createCell(6).setCellValue(customerLevelKV.getKeyValue());
					}
				}
				if(StringUtils.isNotBlank(customer.getRemarks())){
					currentRow.createCell(7).setCellValue(customer.getRemarks());
				}
				if(StringUtils.isNotBlank(customer.getProvinceId())){
					MedicalProvince province = (MedicalProvince) this.iBaseDao.getObject(MedicalProvince.class, customer.getProvinceId());
					if(null != province){
						currentRow.createCell(8).setCellValue(province.getpName());
					}
				}
				if(StringUtils.isNotBlank(customer.getCityId())){
					MedicalCity city = (MedicalCity) this.iBaseDao.getObject(MedicalCity.class, customer.getCityId());
					currentRow.createCell(9).setCellValue(city.getcName());
				}
				if(StringUtils.isNotBlank(customer.getDistrictId())){
					MedicalDistrict district = (MedicalDistrict) this.iBaseDao.getObject(MedicalDistrict.class, customer.getDistrictId());
					if(null != district){
						currentRow.createCell(10).setCellValue(district.getdName());
					}
				}
				if(StringUtils.isNotBlank(customer.getAddress())){
					currentRow.createCell(11).setCellValue(customer.getAddress());
				}
			}
		}
		return workbook;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Workbook exportMyCustomer(MedicalAdmin admin) throws Exception {
		// 获得记录
		List<MedicalCallCustomer> list = this.iBaseDao.getBySql("from MedicalCallCustomer m  where 1=1 and m.userId=? and m.hospitalId=? ", null,admin.getId(), admin.getEnterpriseId());
		// Excel模版对象
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_CALL_CUSTOMER);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}	
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();
		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		// 遍历
		for (MedicalCallCustomer customer : list) {
			i++;
			Row currentRow = sheet.createRow(i);
			if(customer.getSerialNum() != null){
				currentRow.createCell(0).setCellValue(customer.getSerialNum());
			}
			if(customer.getName() != null){
				currentRow.createCell(1).setCellValue(customer.getName());
			}
			if(customer.getSex() != null){
				MedicalKeyValue keyVal = (MedicalKeyValue)this.iBaseDao.getValueByKey(admin.getEnterpriseId(), customer.getSex());
				currentRow.createCell(2).setCellValue(keyVal.getKeyValue());
			}
			if(customer.getCustomersSource() != null){
				MedicalKeyValue keyVal = (MedicalKeyValue)this.iBaseDao.getValueByKey(admin.getEnterpriseId(), customer.getCustomersSource());
				currentRow.createCell(5).setCellValue(keyVal.getKeyValue());
			}
			if(customer.getRecordingTime() != null){
				currentRow.createCell(6).setCellValue(customer.getRecordingTime());
			}
			if(customer.getCustomerServiceId() != null){
				currentRow.createCell(7).setCellValue(customer.getCustomerServiceId());
			}
			if(customer.getCustomerLevel() != null){
				MedicalKeyValue keyVal = (MedicalKeyValue)this.iBaseDao.getValueByKey(admin.getEnterpriseId(), customer.getCustomerLevel());
				currentRow.createCell(8).setCellValue(keyVal.getKeyValue());
			}
			if(customer.getRemarks() != null){
				currentRow.createCell(9).setCellValue(customer.getRemarks());
			}
			//
				currentRow.createCell(10).setCellValue("大白菜");
			
			if(customer.getProvinceId() != null){
				currentRow.createCell(11).setCellValue(customer.getProvinceId());
			}
			if(customer.getCityId() != null){
				currentRow.createCell(12).setCellValue(customer.getCityId());
			}
			if(customer.getDistrictId() != null){
				currentRow.createCell(13).setCellValue(customer.getDistrictId());
			}
			if(customer.getAddress() != null){
				currentRow.createCell(14).setCellValue(customer.getAddress());
			}
			if(customer.getMoney() != null){
				currentRow.createCell(15).setCellValue(customer.getMoney().toString());
			}
			if(customer.getRedEnvelopes() != null){
				currentRow.createCell(16).setCellValue(customer.getRedEnvelopes());
			}
			if(customer.getIntegral() != null){
				currentRow.createCell(17).setCellValue(customer.getIntegral());
			}
			if(customer.getRecommendId() != null){
				currentRow.createCell(18).setCellValue(customer.getRecommendId());
			}
		}
		return workbook;
	}

	@Override
	public Workbook currentExportMyCustomer(MedicalAdmin admin, String ids) throws Exception {
		// Excel模版对象
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_CALL_CUSTOMER);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}	
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();
		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		if(StringUtils.isNotBlank(ids)){
			String [] ordersIds =  ids.split(",");
			for(int j=0;j<ordersIds.length;j++){
				// 获得记录
				MedicalCallCustomer customer = (MedicalCallCustomer)this.iBaseDao.getObject(MedicalCallCustomer.class, ordersIds[j]);
				i++;
				Row currentRow = sheet.createRow(i);
				if(customer.getSerialNum() != null){
					currentRow.createCell(0).setCellValue(customer.getSerialNum());
				}
				if(customer.getName() != null){
					currentRow.createCell(1).setCellValue(customer.getName());
				}
				if(customer.getSex() != null){
					MedicalKeyValue keyVal = (MedicalKeyValue)this.iBaseDao.getValueByKey(admin.getEnterpriseId(), customer.getSex());
					currentRow.createCell(2).setCellValue(keyVal.getKeyValue());
				}
				if(customer.getCustomersSource() != null){
					MedicalKeyValue keyVal = (MedicalKeyValue)this.iBaseDao.getValueByKey(admin.getEnterpriseId(), customer.getCustomersSource());
					currentRow.createCell(5).setCellValue(keyVal.getKeyValue());
				}
				if(customer.getRecordingTime() != null){
					currentRow.createCell(6).setCellValue(customer.getRecordingTime());
				}
				if(customer.getCustomerServiceId() != null){
					currentRow.createCell(7).setCellValue(customer.getCustomerServiceId());
				}
				if(customer.getCustomerLevel() != null){
					MedicalKeyValue keyVal = (MedicalKeyValue)this.iBaseDao.getValueByKey(admin.getEnterpriseId(), customer.getCustomerLevel());
					currentRow.createCell(8).setCellValue(keyVal.getKeyValue());
				}
				if(customer.getRemarks() != null){
					currentRow.createCell(9).setCellValue(customer.getRemarks());
				}
				//
					currentRow.createCell(10).setCellValue("大白菜");
				
				if(customer.getProvinceId() != null){
					currentRow.createCell(11).setCellValue(customer.getProvinceId());
				}
				if(customer.getCityId() != null){
					currentRow.createCell(12).setCellValue(customer.getCityId());
				}
				if(customer.getDistrictId() != null){
					currentRow.createCell(13).setCellValue(customer.getDistrictId());
				}
				if(customer.getAddress() != null){
					currentRow.createCell(14).setCellValue(customer.getAddress());
				}
				if(customer.getMoney() != null){
					currentRow.createCell(15).setCellValue(customer.getMoney().toString());
				}
				if(customer.getRedEnvelopes() != null){
					currentRow.createCell(16).setCellValue(customer.getRedEnvelopes());
				}
				if(customer.getIntegral() != null){
					currentRow.createCell(17).setCellValue(customer.getIntegral());
				}
				if(customer.getRecommendId() != null){
					currentRow.createCell(18).setCellValue(customer.getRecommendId());
				}
			
			}
		}
		return workbook;
	}

	@Override
	public Page findReminderByPage(MedicalAdmin admin, MedicalCallCustomerReminder reminder, Map<String, Object> map) {
		List<Object> objectList = new ArrayList<Object>();
		StringBuilder countSql = new StringBuilder("select count(*) from MedicalCallCustomerReminder m where 1=1 and m.hospitalId=? ");
		StringBuilder statusSql = new StringBuilder("from MedicalCallCustomerReminder m where 1=1 and m.hospitalId=? ");
		objectList.add(admin.getEnterpriseId());
		// 排序
		String[] sortField = (String[]) map.get("sortField");
		String[] sortOrder = (String[]) map.get("sortOrder");
		if(StringUtils.isNotBlank(sortField[0]) && StringUtils.isNotBlank(sortOrder[0])) {
			statusSql.append("order by m." + sortField[0] + " " + sortOrder[0]);
		} else {
			statusSql.append("order by m.createTime desc ");
		}
		
		Page page = this.iBaseDao.getPage(ParamUtil.getInteger(map,"pageIndex",1),ParamUtil.getInteger(map, "pageSize", 20),
				map, countSql.toString(), statusSql.toString(), objectList);
		@SuppressWarnings("unchecked")
		List<MedicalCallCustomerReminder> list = (List<MedicalCallCustomerReminder>) page.getResult();
		for (MedicalCallCustomerReminder medicalCallCustomerReminder : list) {
			MedicalCallCustomer callCustomer = (MedicalCallCustomer) this.iBaseDao.getObject(MedicalCallCustomer.class, medicalCallCustomerReminder.getCustomerId());
			medicalCallCustomerReminder.setCustomerName(callCustomer.getName());
			MedicalAdmin medicalAdmin = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, medicalCallCustomerReminder.getOperatorId());
			medicalCallCustomerReminder.setOperatorUser(medicalAdmin.getName());
			MedicalKeyValue keyValue = this.iBaseDao.getValueByKey(admin.getEnterpriseId(), medicalCallCustomerReminder.getCycle());
			medicalCallCustomerReminder.setCycleVal(keyValue.getKeyValue());
		}
		return page;
	}

	@Override
	public Page findMyReminderByPage(MedicalAdmin admin, MedicalCallCustomerReminder reminder, Map<String, Object> map) {
		List<Object> objectList = new ArrayList<Object>();
		StringBuilder countSql = new StringBuilder("select count(*) from MedicalCallCustomerReminder m where 1=1 and m.operatorId=? and m.hospitalId=? ");
		StringBuilder statusSql = new StringBuilder("from MedicalCallCustomerReminder m where 1=1 and m.operatorId=? and m.hospitalId=? ");
		objectList.add(admin.getId());
		objectList.add(admin.getEnterpriseId());
		
		// 排序
		String[] sortField = (String[]) map.get("sortField");
		String[] sortOrder = (String[]) map.get("sortOrder");
		if(StringUtils.isNotBlank(sortField[0]) && StringUtils.isNotBlank(sortOrder[0])) {
			statusSql.append("order by m." + sortField[0] + " " + sortOrder[0]);
		} else {
			statusSql.append("order by m.createTime desc ");
		}
		
		Page page = this.iBaseDao.getPage(ParamUtil.getInteger(map,"pageIndex",1),ParamUtil.getInteger(map, "pageSize", 20),
				map, countSql.toString(), statusSql.toString(), objectList);
		@SuppressWarnings("unchecked")
		List<MedicalCallCustomerReminder> list = (List<MedicalCallCustomerReminder>) page.getResult();
		for (MedicalCallCustomerReminder medicalCallCustomerReminder : list) {
			MedicalCallCustomer callCustomer = (MedicalCallCustomer) this.iBaseDao.getObject(MedicalCallCustomer.class, medicalCallCustomerReminder.getCustomerId());
			medicalCallCustomerReminder.setCustomerName(callCustomer.getName());
			MedicalAdmin medicalAdmin = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, medicalCallCustomerReminder.getOperatorId());
			medicalCallCustomerReminder.setOperatorUser(medicalAdmin.getName());
			MedicalKeyValue keyValue = this.iBaseDao.getValueByKey(admin.getEnterpriseId(), medicalCallCustomerReminder.getCycle());
			medicalCallCustomerReminder.setCycleVal(keyValue.getKeyValue());
		}
		return page;
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
	public void editSave(MedicalCallCustomerReminder reminder) {
		MedicalCallCustomerReminder remind = (MedicalCallCustomerReminder) this.iBaseDao.getObject(MedicalCallCustomerReminder.class, reminder.getId());
		remind.setContent(reminder.getContent());
		remind.setCycle(reminder.getCycle());
		remind.setOperatorId(reminder.getOperatorId());
		remind.setReminderTime(reminder.getReminderTime());
		this.iBaseDao.saveObject(remind);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Workbook exportRemind(MedicalAdmin admin) throws Exception {
		// 获得记录
		List<MedicalCallCustomerReminder> list = this.iBaseDao.getBySql("from MedicalCallCustomerReminder m  where 1=1 and m.hospitalId=? ", null, admin.getEnterpriseId());
		// Excel模版对象
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_CALL_REMIND);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}	
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();
		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		// 遍历
		for (MedicalCallCustomerReminder reminder : list) {
			i++;
			Row currentRow = sheet.createRow(i);
			if(reminder.getOperatorId() != null){
				MedicalAdmin medicalAdmin = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, reminder.getOperatorId());
				currentRow.createCell(0).setCellValue(medicalAdmin.getName());
			}
			if(reminder.getCustomerId() != null){
				MedicalCallCustomer callCustomer = (MedicalCallCustomer) this.iBaseDao.getObject(MedicalCallCustomer.class, reminder.getCustomerId());
				currentRow.createCell(1).setCellValue(callCustomer.getName());
			}
			if(reminder.getContent() != null){
				currentRow.createCell(2).setCellValue(reminder.getContent());
			}
			if(reminder.getReminderTime() != null){
				currentRow.createCell(3).setCellValue(reminder.getReminderTime());
			}
			if(reminder.getCycle() != null){
				MedicalKeyValue keyValue = this.iBaseDao.getValueByKey(admin.getEnterpriseId(), reminder.getCycle());
				currentRow.createCell(4).setCellValue(keyValue.getKeyValue());
			}
		}
		return workbook;
	}

	@Override
	public Workbook currentExportRemind(MedicalAdmin admin, String ids) throws Exception {
		// Excel模版对象
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_CALL_REMIND);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}	
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();
		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		if(StringUtils.isNotBlank(ids)){
			String [] ordersIds =  ids.split(",");
			for(int j=0;j<ordersIds.length;j++){
				// 获得记录
				MedicalCallCustomerReminder reminder = (MedicalCallCustomerReminder)this.iBaseDao.getObject(MedicalCallCustomerReminder.class, ordersIds[j]);
				i++;
				Row currentRow = sheet.createRow(i);
				if(reminder.getOperatorId() != null){
					MedicalAdmin medicalAdmin = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, reminder.getOperatorId());
					currentRow.createCell(0).setCellValue(medicalAdmin.getName());
				}
				if(reminder.getCustomerId() != null){
					MedicalCallCustomer callCustomer = (MedicalCallCustomer) this.iBaseDao.getObject(MedicalCallCustomer.class, reminder.getCustomerId());
					currentRow.createCell(1).setCellValue(callCustomer.getName());
				}
				if(reminder.getContent() != null){
					currentRow.createCell(2).setCellValue(reminder.getContent());
				}
				if(reminder.getReminderTime() != null){
					currentRow.createCell(3).setCellValue(reminder.getReminderTime());
				}
				if(reminder.getCycle() != null){
					MedicalKeyValue keyValue = this.iBaseDao.getValueByKey(admin.getEnterpriseId(), reminder.getCycle());
					currentRow.createCell(4).setCellValue(keyValue.getKeyValue());
				}
			
			}
		}
		return workbook;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Workbook exportMyRemind(MedicalAdmin admin) throws Exception {
		// 获得记录
		List<MedicalCallCustomerReminder> list = this.iBaseDao.getBySql("from MedicalCallCustomerReminder m  where m.operatorId=? and m.hospitalId=? ", null,admin.getId(), admin.getEnterpriseId());
		// Excel模版对象
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_CALL_REMIND);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}	
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();
		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		// 遍历
		for (MedicalCallCustomerReminder reminder : list) {
			i++;
			Row currentRow = sheet.createRow(i);
			if(reminder.getOperatorId() != null){
				MedicalAdmin medicalAdmin = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, reminder.getOperatorId());
				currentRow.createCell(0).setCellValue(medicalAdmin.getName());
			}
			if(reminder.getCustomerId() != null){
				MedicalCallCustomer callCustomer = (MedicalCallCustomer) this.iBaseDao.getObject(MedicalCallCustomer.class, reminder.getCustomerId());
				currentRow.createCell(1).setCellValue(callCustomer.getName());
			}
			if(reminder.getContent() != null){
				currentRow.createCell(2).setCellValue(reminder.getContent());
			}
			if(reminder.getReminderTime() != null){
				currentRow.createCell(3).setCellValue(reminder.getReminderTime());
			}
			if(reminder.getCycle() != null){
				MedicalKeyValue keyValue = this.iBaseDao.getValueByKey(admin.getEnterpriseId(), reminder.getCycle());
				currentRow.createCell(4).setCellValue(keyValue.getKeyValue());
			}
		}
		return workbook;
	}

	@Override
	public Workbook currentExportMyRemind(MedicalAdmin admin, String ids) throws Exception {
		// Excel模版对象
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_CALL_REMIND);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}	
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();
		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		if(StringUtils.isNotBlank(ids)){
			String [] ordersIds =  ids.split(",");
			for(int j=0;j<ordersIds.length;j++){
				// 获得记录
				MedicalCallCustomerReminder reminder = (MedicalCallCustomerReminder)this.iBaseDao.getObject(MedicalCallCustomerReminder.class, ordersIds[j]);
				i++;
				Row currentRow = sheet.createRow(i);
				if(reminder.getOperatorId() != null){
					MedicalAdmin medicalAdmin = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, reminder.getOperatorId());
					currentRow.createCell(0).setCellValue(medicalAdmin.getName());
				}
				if(reminder.getCustomerId() != null){
					MedicalCallCustomer callCustomer = (MedicalCallCustomer) this.iBaseDao.getObject(MedicalCallCustomer.class, reminder.getCustomerId());
					currentRow.createCell(1).setCellValue(callCustomer.getName());
				}
				if(reminder.getContent() != null){
					currentRow.createCell(2).setCellValue(reminder.getContent());
				}
				if(reminder.getReminderTime() != null){
					currentRow.createCell(3).setCellValue(reminder.getReminderTime());
				}
				if(reminder.getCycle() != null){
					MedicalKeyValue keyValue = this.iBaseDao.getValueByKey(admin.getEnterpriseId(), reminder.getCycle());
					currentRow.createCell(4).setCellValue(keyValue.getKeyValue());
				}
			}
		}
		return workbook;
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void deleteRemind(MedicalCallCustomerReminder reminder) {
		String ids[] = reminder.getId().split(",");
		for(String id : ids) {
			this.iBaseDao.updateHql("delete from MedicalCallCustomerReminder m where m.id = ? ", id);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public String saveCustomer(MedicalCallCustomer callCustomer, MedicalAdmin admin) {
		callCustomer.setHospitalId(admin.getEnterpriseId());
		MedicalProvince province = (MedicalProvince) this.iBaseDao.getObject(MedicalProvince.class, callCustomer.getProvinceId());
		MedicalCity city = (MedicalCity) this.iBaseDao.getObject(MedicalCity.class, callCustomer.getCityId());
		MedicalDistrict district = (MedicalDistrict) this.iBaseDao.getObject(MedicalDistrict.class, callCustomer.getDistrictId());
		callCustomer.setSerialNum(SerialNumUtil.code());
		callCustomer.setProvince(province);
		callCustomer.setCity(city);
		callCustomer.setDistrict(district);
		Date birthday = callCustomer.getBirthDate();
		if(null != birthday) {
			int age = this.countAge(birthday);
			callCustomer.setAge(age);
		}
		this.iBaseDao.saveObject(callCustomer);
		List<MedicalCallTelInfo> telInfoList = this.iBaseDao.getBySql("from MedicalCallTelInfo a where a.callId=? ", null, callCustomer.getCallId());
		for(MedicalCallTelInfo telInfo : telInfoList) {
			telInfo.setCustomerId(callCustomer.getId());
		}
		return callCustomer.getId();
	}

	@Override
	public MedicalCallCustomer findCustomerByCallId(String callId) {
		return (MedicalCallCustomer) this.iBaseDao.getObjectByHql("from MedicalCallCustomer a where a.callId=? ", callId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalProvince> findProvinceList() {
		return this.iBaseDao.getBySql("from MedicalProvince ", null);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalCity> findCityListByPid(String pId) {
		return this.iBaseDao.getBySql("from MedicalCity a where a.pId=? ", null, pId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalDistrict> findDistrictListByCid(String cId) {
		return this.iBaseDao.getBySql("from MedicalDistrict a where a.cId=? ", null, cId);
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
	public void editCustomer(MedicalCallCustomer customer) {
		MedicalCallCustomer bean = (MedicalCallCustomer) this.iBaseDao.getObject(MedicalCallCustomer.class, customer.getId());
		bean.setName(customer.getName());
		bean.setSex(customer.getSex());
		bean.setBirthDate(customer.getBirthDate());
		bean.setCustomerLevel(customer.getCustomerLevel());
		bean.setCustomersSource(customer.getCustomersSource());
		bean.setJournal(customer.getJournal());
		MedicalProvince province = (MedicalProvince) this.iBaseDao.getObject(MedicalProvince.class, customer.getProvinceId());
		MedicalCity city = (MedicalCity) this.iBaseDao.getObject(MedicalCity.class, customer.getCityId());
		MedicalDistrict district = (MedicalDistrict) this.iBaseDao.getObject(MedicalDistrict.class, customer.getDistrictId());
		bean.setProvince(province);
		bean.setCity(city);
		bean.setDistrict(district);
		bean.setAddress(customer.getAddress());
		bean.setZipCode(customer.getZipCode());
		bean.setMoney(customer.getMoney());
		bean.setIntegral(customer.getIntegral());
		bean.setRedEnvelopes(customer.getRedEnvelopes());
		bean.setRecommendId(customer.getRecommendId());
		bean.setRemarks(customer.getRemarks());
		if(null != customer.getBirthDate()) {
			int age = this.countAge(customer.getBirthDate());
			bean.setAge(age);
		}
		bean.setUpdateTime(new Date());
	}

	@Override
	public Page findRecCustomerList(MedicalAdmin admin, MedicalCallCustomer customer, Map<String, Object> map) {
		List<Object> objectList = new ArrayList<Object>();
		StringBuilder countSql = new StringBuilder("select count(*) from MedicalCallCustomer m where m.hospitalId=? ");
		StringBuilder statusSql = new StringBuilder("from MedicalCallCustomer m where m.hospitalId=? ");
		objectList.add(admin.getEnterpriseId());
		
		if(StringUtils.isNotBlank(customer.getId())) {
			countSql.append("and m.id <> ? ");
			statusSql.append("and m.id <> ? ");
			objectList.add(customer.getId());
		}
		
		if(StringUtils.isNotBlank(customer.getName())){
			countSql.append("and m.name like ? ");
			statusSql.append("and m.name like ? ");
			objectList.add("%"+customer.getName()+"%");
		}
		
		if(StringUtils.isNotBlank(customer.getContactNo())){
			MedicalCallTelInfo callTelInfo = (MedicalCallTelInfo) this.iBaseDao.getObjectByHql("from MedicalCallTelInfo a where a.eid=? and a.phoneNum=? ", admin.getEnterpriseId(), customer.getContactNo());
			if(callTelInfo != null){
				countSql.append("and m.id = ? ");
				statusSql.append("and m.id = ? ");
				objectList.add(callTelInfo.getCustomerId());
			}else{
				countSql.append("and m.id = null ");
				statusSql.append("and m.id = null ");
			}
		}
		
		
		statusSql.append("order by m.createTime desc ");
		Page page = this.iBaseDao.getPage(ParamUtil.getInteger(map,"pageIndex",1),ParamUtil.getInteger(map, "pageSize", 20),
				map, countSql.toString(), statusSql.toString(), objectList);
		
		@SuppressWarnings("unchecked")
		List<MedicalCallCustomer> list = (List<MedicalCallCustomer>) page.getResult();
		for (MedicalCallCustomer medicalCallCustomer : list) {
			@SuppressWarnings("unchecked")
			List<MedicalCallTelInfo> tempList = this.iBaseDao.getBySql("from MedicalCallTelInfo a where a.eid=? and a.customerId=? ", null, medicalCallCustomer.getHospitalId(), medicalCallCustomer.getId());
			String tempContactNo = "";
			for (MedicalCallTelInfo medicalCallTelInfo : tempList) {
				tempContactNo += medicalCallTelInfo.getPhoneNum() + ",";
			}
			tempContactNo = tempContactNo.substring(0, tempContactNo.length() - 1);
			medicalCallCustomer.setContactNo(tempContactNo);
		}
		return page;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public MedicalCallCustomer findCustomerById(MedicalCallCustomer customer, MedicalAdmin admin) {
		MedicalCallCustomer bean = (MedicalCallCustomer) this.iBaseDao.getObject(MedicalCallCustomer.class, customer.getId());
		MedicalKeyValue keyVal = this.iBaseDao.getValueByKey(admin.getEnterpriseId(), bean.getCustomerLevel());
		if(null != keyVal) {
			bean.setKeyCustomerLevel(keyVal.getKeyValue());
		}
		
		StringBuilder outSideNum = new StringBuilder("");
		MedicalCall call = (MedicalCall) this.iBaseDao.getObject(MedicalCall.class, bean.getCallId());
		if(null != call && StringUtils.isNotBlank(call.getOutsideNum())) {
			outSideNum.append(call.getOutsideNum());
		} else if(null == call) {
			MedicalCallUntreated callUnt = (MedicalCallUntreated) this.iBaseDao.getObject(MedicalCallUntreated.class, bean.getCallId());
			if(null != callUnt && StringUtils.isNotBlank(callUnt.getOutsideNum())) {
				outSideNum.append(callUnt.getOutsideNum());
			
			} else if(null == callUnt) {
				MedicalCallPending callPen = (MedicalCallPending) this.iBaseDao.getObject(MedicalCallPending.class, bean.getCallId());
				if(null != callPen && StringUtils.isNotBlank(callPen.getOutsideNum())) {
					outSideNum.append(callPen.getOutsideNum());
				
				} else if(null == callPen) {
					MedicalCallEnd callEnd = (MedicalCallEnd) this.iBaseDao.getObject(MedicalCallEnd.class, bean.getCallId());
					if(null != callEnd && StringUtils.isNotBlank(callEnd.getOutsideNum())) {
						outSideNum.append(callEnd.getOutsideNum());
					
					} else if(null == callEnd) {
						MedicalCallTerminate callTer = (MedicalCallTerminate) this.iBaseDao.getObject(MedicalCallTerminate.class, bean.getCallId());
						if(null != callTer && StringUtils.isNotBlank(callTer.getOutsideNum())) {
							outSideNum.append(callTer.getOutsideNum());
						}
					}
					
				}
			}
		}
		if(StringUtils.isNotBlank(outSideNum)) {
			List<MedicalMediaPlacement>  list = this.iBaseDao.getBySql("from MedicalMediaPlacement a where a.publishNumbers=? ", null, outSideNum.toString());
			Set<String> mediaIdSet = new HashSet<String>();
			for(MedicalMediaPlacement mediaPlacement : list) {
				mediaIdSet.add(mediaPlacement.getMedia().getId());
			}
			if(mediaIdSet.size() == 1) {
				bean.setMedia(new ArrayList(mediaIdSet).get(0).toString());
			}
		}
		
		// 包含审核通过单设置订单性质为复购
		List<MedicalOrdersStorage> ordersList = this.iBaseDao.getBySql("from MedicalOrdersStorage a where a.customerId=? ", null, bean.getId());
		boolean flag = false;
		for(MedicalOrdersStorage orders : ordersList) {
			if(SystemConfig.ORDERS_AUDIT_PASS_TYPE.equals(orders.getOrdersStatus())) {
				flag = true;
				break;
			}
		}
		if(flag) {
			bean.setOrdersNature(SystemConfig.ORDER_NATURE_TYPE);
		}
		return bean;
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void editCustomerLevel(MedicalCallCustomer customer) {
		MedicalCallCustomer bean = (MedicalCallCustomer) this.iBaseDao.getObject(MedicalCallCustomer.class, customer.getId());
		bean.setCustomerLevel(customer.getCustomerLevel());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalCallContactRecord> findContactRecordList(String cId) {
		List<MedicalCallContactRecord> list = this.iBaseDao.getBySql("from MedicalCallContactRecord a where a.customerId=? order by a.contactTime desc ", null, cId);
		List<MedicalCallContactRecord> list1 = new ArrayList<MedicalCallContactRecord>();
		for(MedicalCallContactRecord contactRecord : list) {
			MedicalAdmin admin = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, contactRecord.getOperatorId());
			String operatorUser = admin.getUsername() + "/" + admin.getName();
			contactRecord.setOperatorUser(operatorUser);
			list1.add(contactRecord);
		}
		return list1;
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void saveContactRecord(MedicalCallContactRecord contactRecord) {
		this.iBaseDao.saveObject(contactRecord);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalCallCustomerReminder> findCustomeRemindByCId(String cId) {
		List<MedicalCallCustomerReminder> list = this.iBaseDao.getBySql("from MedicalCallCustomerReminder a where a.customerId=? order by a.createTime desc ", null, cId);
		List<MedicalCallCustomerReminder> list1 = new ArrayList<MedicalCallCustomerReminder>();
		for(MedicalCallCustomerReminder customerReminder : list) {
			MedicalAdmin admin = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, customerReminder.getOperatorId());
			customerReminder.setOperatorUser(admin.getUsername());
			MedicalKeyValue cycle = this.iBaseDao.getValueByKey(customerReminder.getHospitalId(), customerReminder.getCycle());
			customerReminder.setCycleVal(cycle.getKeyValue());
			list1.add(customerReminder);
		}
		return list1;
	}

	@Override
	@Transactional(propagation = Propagation.NEVER)
	public void saveCustomeRemind(MedicalCallCustomerReminder customerReminder) {
		this.iBaseDao.saveObject(customerReminder);
		MedicalAdmin user = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		httpRequestUtil.connect(customerReminder.getCycle(),customerReminder.getReminderTime(),customerReminder.getOperatorId(),customerReminder.getContent(),user.getEnterpriseId());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalCallCustomer> findRecommendCustomer(String cId) {
		List<MedicalCallCustomer> list = this.iBaseDao.getBySql("from MedicalCallCustomer a where a.recommendId=? ", null, cId);
		List<MedicalCallCustomer> customerList = new ArrayList<MedicalCallCustomer>();
		for (MedicalCallCustomer customer : list) {
			MedicalCallTelInfo telInfo = (MedicalCallTelInfo) this.iBaseDao.getObjectByHql("from MedicalCallTelInfo a where a.customerId=? and a.isMain=? ", customer.getId(), SystemConfig.CUSTOMER_TEL_IS_MAIN);
			if(null != telInfo) {
				customer.setContactNo(telInfo.getPhoneNum());
			}
			customerList.add(customer);
		}
		return customerList;
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public String customerSave(MedicalAdmin admin, MedicalCallCustomer callCustomer) {
		callCustomer.setHospitalId(admin.getEnterpriseId());
		callCustomer.setSerialNum(SerialNumUtil.code());
		this.iBaseDao.saveObject(callCustomer);
		return callCustomer.getId();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalCallCustomerHealth> customerHealthView(String cId) {
		List<MedicalCallCustomerHealth> list = this.iBaseDao.getBySql("from MedicalCallCustomerHealth a where a.customerId=? order by a.createTime desc ", null, cId);
		List<MedicalCallCustomerHealth> list1 = new ArrayList<MedicalCallCustomerHealth>();
		for(MedicalCallCustomerHealth bean : list) {
			MedicalAdmin admin = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, bean.getAttendantId());
			bean.setAttendantName(admin.getUsername());
			list1.add(bean);
		}
		return list1;
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void saveCustomerHealth(MedicalCallCustomerHealth customerHealth) {
		MedicalCallHealthSymptom healthSymptom = (MedicalCallHealthSymptom) this.iBaseDao.getObject(MedicalCallHealthSymptom.class, customerHealth.getHealthArchiveId());
		customerHealth.setHealthSymptom(healthSymptom);
		this.iBaseDao.saveObject(customerHealth);
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void delCustomerHealth(MedicalCallCustomerHealth customerHealth) {
		this.iBaseDao.deleteObject(customerHealth);
	}
	
	/**
	 * @desc 计算年龄
	 * @return int
	 * @author liy
	 * @datetime 2015年1月4日,上午11:38:55
	 */
	private int countAge(Date birthday) {
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);	// 当前年份
		String byear = DateFormatUtils.format(birthday, "yyyy");
		int byearNum = Integer.valueOf(byear);
		
		return year - byearNum;
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void importToCall(MedicalAdmin admin, MedicalCallCustomer customer) {
		
		String cIds[] = customer.getId().split(",");
		String customerNos[] = customer.getContactNo().split(",");
		
		for(int i=0; i<cIds.length; i++) {
			MedicalCall call = new MedicalCall();
			String uid = UUID.randomUUID().toString();
			String id = uid.replace("-", "");
			call.setSerialNum(SerialNumUtil.code());
			call.setId(id);
			call.setRelatedPhone(customerNos[i]);
			call.setCategory(SystemConfig.CALL_FIRST_TYPE);
			call.setIncomingCount(0);
			call.setCreateUser(admin.getId());
			call.setHospitalId(admin.getEnterpriseId());
			call.setGrade(SystemConfig.CALL_TASK_GRADE_INIT);
			this.iBaseDao.addObject(call);
			this.iBaseDao.updateHql("update MedicalCallCustomer a set a.callId=? where a.id=? ", call.getId(), cIds[i]);
			this.iBaseDao.updateHql("update MedicalCallTelInfo a set a.callId=? where a.customerId=? ", call.getId(), cIds[i]);
		}
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void setBackCount(MedicalCallCustomer customer) {
		this.iBaseDao.updateHql("update MedicalKeyValue a set a.keyValue=? where a.typeName=? and a.hospitalId=? ", customer.getBackCount(), SystemConfig.SET_BACK_COUNT_TYPE, customer.getHospitalId());
	}

	@Override
	public String findBackCount(MedicalCallCustomer customer) {
		MedicalKeyValue keyVal = (MedicalKeyValue) this.iBaseDao.getObjectByHql("from MedicalKeyValue a where a.typeName=? and a.hospitalId=? ", SystemConfig.SET_BACK_COUNT_TYPE, customer.getHospitalId());
		return keyVal.getKeyValue();
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void delNewCustomer(MedicalCallCustomer customer) {
		this.iBaseDao.updateHql("delete MedicalCallTelInfo a where a.customerId=? ", customer.getId());
		this.iBaseDao.deleteObject(customer);
	}
	
}
